<?php

namespace System\Core;

use System\core\Safety;
use System\Exceptions\Handler;

class App
{

    public function run()
    {
        // 确保编译目录存在
        if (!is_dir(BASE_PATH . '/templates_c')) {
            mkdir(BASE_PATH . '/templates_c', 0755, true);
        }

        // 确保日志目录存在
        if (!is_dir(BASE_PATH . '/storage/logs')) {
            mkdir(BASE_PATH . '/storage/logs', 0755, true);
        }

        // 加载辅助函数
        require SYS_PATH . '/helpers.php';

        // 加载环境变量
        Config::loadEnv(BASE_PATH . '/.env');
        Config::load();

        // 启动会话
        Session::start();

        // 初始化日志系统
        $log = Log::getInstance();

        // 设置异常处理
        set_exception_handler([$this, 'handleException']);

        try {
            Safety::httpSafe();
            // 创建请求对象
            $request = Request::capture();

            // 记录框架启动日志
            log_info('Framework started', [
                'uri' => $request->uri(),
                'method' => $request->method(),
                'ip' => $request->ip()
            ]);

            // 创建路由对象
            $router = new Router();

            // 包含路由定义
            require APP_PATH . '/routes.php';

            // 执行路由
            $response = $router->dispatch($request);

            if(empty($response)){
                return;
            }

            // 发送响应
            $response->send();
        } catch (\Throwable $e) {
            $this->handleException($e);
        }
    }

    public function handleException($e)
    {
        $handler = new Handler();
        $handler->report($e);

        $request = Request::capture();
        $response = $handler->render($request, $e);

        $response->send();
        exit(1);
    }
}
